use yew::{platform::spawn_local, prelude::*};
use yew_router::prelude::*;

use crate::{
  api::crates::api_crates_delete,
  components::{alert::Alert, header::Header},
  contexts::CurrentUserContext,
  pages::slidebar::Slidebar,
  Route,
};

#[derive(Properties, PartialEq)]
pub struct Props {
  pub crates_id: i32,
}

#[function_component]
pub fn CratesDelete(props: &Props) -> Html {
  let navigator = use_navigator().expect("Navigator not available");
  let current_user_ctx = use_context::<CurrentUserContext>()
    .expect("Current user context is missing");

  let error_message_hander = use_state(String::default);
  let error_message = (*error_message_hander).clone();
  let cloned_id = props.crates_id.clone();

  match &current_user_ctx.token {
    Some(token) => {
      let cloned_id = cloned_id.clone();
      let cloned_token = token.to_owned();

      let onclick = {
        move |e: MouseEvent| {
          e.prevent_default();

          let c_navigator = navigator.clone();
          let c_error_message_hander = error_message_hander.clone();
          let cloned_token = cloned_token.clone();

          spawn_local(async move {
            match api_crates_delete(&cloned_token, cloned_id).await {
              Ok(_) => c_navigator.push(&Route::Crates),
              Err(err) => c_error_message_hander.set(err.to_string()),
            }
          });
        }
      };

      html! {
        <>
        <Header/>
        <Slidebar/>
        <div>
          if error_message.len() > 0 {
            <Alert message={error_message} alert_type="error"/>
          }
          <b>{ "Are you sure you want to delete crates #" }</b>
          <i>{ props.crates_id.clone() }</i>
          <p><button {onclick}>{"Delete"}</button></p>
        </div>
      </>
      }
    }
    None => html! {
      <Redirect<Route> to={Route::Login}/>
    },
  }
}
